package com.atguigu.juc.chap04;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

public class NotSafeDemo {

    public static void main(String[] args) {

        listDemo();

        setDemo();

        mapDemo();
    }

    private static void listDemo() {
        // 线程不安全
        // List<String> list = new ArrayList<>();

        // Vector 线程安全
        // Vector<String> list = new Vector<>();

        // Collections.synchronizedList 包装 线程安全
        // List<String> list = Collections.synchronizedList(new ArrayList<>());

        List<String> list = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));// 线程不安全
                System.out.println(list);// 调用了ArrayList的迭代方法
            }, String.valueOf(i)).start();
        }
    }


    private static void setDemo() {
        // 线程不安全
        // Set<String> set = new HashSet<>();

        // 线程安全
        // Set<String> set = Collections.synchronizedSet(new HashSet<>());

        // 线程安全
        Set<String> set = new CopyOnWriteArraySet<>();

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            }, String.valueOf(i)).start();
        }
    }

    private static void mapDemo() {

        // 线程不安全
        // Map<String, String> map = new HashMap<>();

        // 线程安全 全局锁
        // Map<String, String> map = new Hashtable<>();

        // 线程安全
        // Map<String, String> map = Collections.synchronizedMap(new HashMap<>());

        // 线程安全 分段锁
        Map<String, String> map = new ConcurrentHashMap<>();


        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                map.put(String.valueOf(Thread.currentThread().getName()), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
    }
}